package awk.jndi;

import javax.naming.Context;
import javax.naming.InitialContext;

/**
 * @description:
 * @author: wanghaifeng
 * @date: 2021/3/1
 *
 * 程序中jbossJndi.properties文件的内容为
 * java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
 * java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
 * java.naming.provider.url=jnp://localhost:1099
 *  注意:要正确运行示例程序,请启动jboss,并将jboss的jbossall-client.jar文件放入classpath中。
 *
 * 上述示例程序在jboss服务器的jndi树上建立了几个上下文,并bind了几对象
 */
public class TestJbossJNDI {
    public TestJbossJNDI() {
        super();
    }
    public static void main(String[] args) {
        try {
            //载入jboss的SPI相关参数,包括初始上下文工厂，服务URL，等等，需要有jboss环境
       /*     Properties env = new Properties();
            env.load(new FileInputStream("jndi.properties"));
            env.list(System.out);*/
            Context ctx = new InitialContext();
            System.out.println("Got context");
            //create a subContext
            ctx.createSubcontext("/sylilzy");
            ctx.createSubcontext("sylilzy/sily");
            //rebind a object
            ctx.rebind("sylilzy/sily/a", "I am sily a!");
            ctx.rebind("sylilzy/sily/b", "I am sily b!");

            //lookup context
            Context ctx1=(Context)ctx.lookup("sylilzy");
            Context ctx2=(Context)ctx1.lookup("/sylilzy/sily");
            ctx2.bind("/sylilzy/g", "this is g");
            //lookup binded object
            Object o=ctx1.lookup("sily/a");
            System.out.println("get object from jndi:"+"get object from jndi:"+o);
            //rename the object
            ctx2.rename("/sylilzy/g", "g1");
            o=ctx2.lookup("g1");
            System.out.println("get object from jndi:"+"get object from jndi:"+o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}